<?php
require_once "../api/article.php";
require_once "../utils/Response.php";
require_once "../api/mentals.php";
//require_once "../api/file.php";
$request_method = $_SERVER['REQUEST_METHOD'];

if ($request_method === 'POST') {
    // 获取POST数据
    $postData = $_POST;

    // 处理文章相关的请求
    if (isset($postData['action'])) {
        switch ($postData['action']) {
            case 'createArticle':
                createArticle($postData);
                break;
            case 'updateArticle':
                updateArticle($postData);
                break;
            case 'deleteArticle':
                if (isset($postData['id']) && !empty($postData['id'])) {
                    deleteArticleById($postData['id']);
                } else {
                    Response::error('删除文章失败：缺少文章ID')->send();
                }
                break;
            default:
                // 无效的action参数
                Response::error('无效的action参数: ' . $postData['action'])->send();
        }
    } else {
        // 如果没有指定action参数
        Response::error('缺少必要的action参数')->send();
    }
} elseif ($request_method === 'GET') {
    if ($_GET["mentalId"]) {
        $mentalId = $_GET["mentalId"];
        getMentalById($mentalId);
    }
} elseif ($request_method === 'DELETE') {
    // 获取DELETE请求的数据
    // parse_str(file_get_contents('php://input'), $deleteData);

    // 从URL参数中获取文章ID
    if (isset($_GET['id']) && !empty($_GET['id'])) {
        deleteArticleById($_GET['id']);
    }
    // 从请求体中获取文章ID
    elseif (isset($deleteData['id']) && !empty($deleteData['id'])) {
        deleteArticleById($deleteData['id']);
    }
    else {
        Response::error('删除文章失败：缺少文章ID')->send();
    }
} else {
    // 非POST请求处理
    Response::error('仅支持POST请求')->send();
}

// 确保脚本结束时有输出
if (!headers_sent()) {
    Response::error('未知错误，请联系管理员')->send();
}